﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using cecbData;
using cecbClasses;
using cecbClasses.Data_Classes;
using cecbClasses.Data_Adapters;

namespace CECB
{
    /// <summary>
    /// Interaction logic for AddNewProject_Window.xaml
    /// </summary>
    public partial class AddNewProject_Window : Window
    {
        private bool stopRefreshControls = false;
        private bool dataChanged = false;
        string destFile;
        string destFile1;


        Func_Projects ObjProjcts;


        List<Data_ProjectGridLocation> listObjGrdLoc = new List<Data_ProjectGridLocation>();
        public AddNewProject_Window()
        {
            InitializeComponent();
            ObjProjcts = new Func_Projects();
            lblConsultent.Content = "CECB";
           // combobox_TeamLeader.ItemsSource = new Dss.Methods.ProjectTeam().getTeamLeaders();
        }




        public void FillPrjCategories()
        {
            List<Categories> CatgryList = ObjProjcts.GetAllCatogries();
            comboBox_projCatogory.ItemsSource = CatgryList;
        }


        public void FillPrjType()
        {

            List<cecbData.ProjectTypes> ProjectTypeList = ObjProjcts.GetAllProjectTypes();
            comboBox_projType.ItemsSource = ProjectTypeList; ;
        }


        private void button5_Click(object sender, RoutedEventArgs e)
        {

        }


        private void button_save_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                ObjProjcts = new Func_Projects();
                Data_Projects ObjProjects = new Data_Projects();

                ObjProjects.Proj_name = textBox_projname.Text;
                if (comboBox_projCatogory.SelectedIndex > -1)
                    ObjProjects.Proj_category = comboBox_projCatogory.SelectedValue.ToString();
                else {
                    MessageBox.Show("Please Select Project Catogry", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                    return; }
                if (comboBox_projType.SelectedIndex > -1)
                    ObjProjects.Proj_type = comboBox_projType.SelectedValue.ToString();
                else {
                    MessageBox.Show("Please Select Project Type", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                ObjProjects.Proj_location = textBox_location.Text;
                ObjProjects.Proj_proponent = textBox_client.Text;
                ObjProjects.Proj_consultant = lblConsultent.Content.ToString();
                ObjProjects.Proj_approvingAgency = textBox_appAgency.Text;
                ObjProjects.Proj_modelImage = destFile1;
                ObjProjects.Proj_planImage = destFile;
                ObjProjects.Proj_otherDetails = tbMultiLine.Text;
                ObjProjects.Proj_status = true;




                if (string.IsNullOrEmpty(textBox_projname.Text))
                {

                    MessageBox.Show("Please Enter Project Name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (string.IsNullOrEmpty(comboBox_projCatogory.Text))
                {

                    MessageBox.Show("Please Select Project Catogry", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                else if (string.IsNullOrEmpty(comboBox_projType.Text))
                {


                    MessageBox.Show("Please Selcet Project Type", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (string.IsNullOrEmpty(textBox_client.Text))
                {

                    MessageBox.Show("Please Enter Project Client", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                //else if (string.IsNullOrEmpty(lblConsultent.Content))
                //{

                //    MessageBox.Show("Please Select Project Consultent", "Message", MessageBoxButton.OK, MessageBoxImage.Error);

                //}
                else if (string.IsNullOrEmpty(textBox_appAgency.Text))
                {

                    MessageBox.Show("Please Enter Project Agency", "Message", MessageBoxButton.OK, MessageBoxImage.Error);

                }
                else if (string.IsNullOrEmpty(textBox_location.Text))
                {

                    MessageBox.Show("Please Enter Project Location", "Message", MessageBoxButton.OK, MessageBoxImage.Error);

                }

                else
                {

                    if (string.IsNullOrEmpty(destFile1))
                    {
                        ObjProjects.Proj_modelImage = "null";


                    }
                    if (string.IsNullOrEmpty(destFile))
                    {
                        ObjProjects.Proj_modelImage = "null";

                    }

                    ObjProjcts.insertIntoProjects(ObjProjects, listObjGrdLoc);

                    MessageBox.Show("Project inserted Successfully", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                }



            }
            catch (Exception ex)
            {


                MessageBox.Show("System Error! " + ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Warning);
                SaveButton.IsEnabled = false;
            }

        }

        private void button_selctModlImg_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog 

            Microsoft.Win32.OpenFileDialog dlg1 = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file extension and default file extension 

            dlg1.DefaultExt = ".jpg";

            dlg1.Filter = "JPG files (*.jpg)|*.jpg|All files (*.*)|*.*";



            // Display OpenFileDialog by calling ShowDialog method 

            Nullable<bool> result = dlg1.ShowDialog();



            // Get the selected file name and display in a TextBox 

            if (result == true)
            {

                // Open document 
                string filename = dlg1.FileName;

                string targetPath = System.IO.Directory.GetCurrentDirectory().ToString();
                targetPath = targetPath + "\\Project_PlanImages_Prj1";


                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                // Use Path class to manipulate file and directory paths. 
                string sourceFile = System.IO.Path.GetFileName(filename);

                destFile1 = System.IO.Path.Combine(targetPath, sourceFile);
                System.IO.File.Copy(filename, destFile1, true);

                image_modelImg.Source = new BitmapImage(new Uri(destFile1));

            }




        }



        private void button_selectPlanImg_Click(object sender, RoutedEventArgs e)
        {// Create OpenFileDialog 

            Microsoft.Win32.OpenFileDialog dlg1 = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file extension and default file extension 

            dlg1.DefaultExt = ".jpg";

            dlg1.Filter = "JPG files (*.jpg)|*.jpg|All files (*.*)|*.*";



            // Display OpenFileDialog by calling ShowDialog method 

            Nullable<bool> result = dlg1.ShowDialog();



            // Get the selected file name and display in a TextBox 

            if (result == true)
            {

                // Open document 
                string filename = dlg1.FileName;

                string targetPath = System.IO.Directory.GetCurrentDirectory().ToString();
                targetPath = targetPath + "\\Project_PlanImages_Prj1";


                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                // Use Path class to manipulate file and directory paths. 
                string sourceFile = System.IO.Path.GetFileName(filename);

                destFile = System.IO.Path.Combine(targetPath, sourceFile);
                System.IO.File.Copy(filename, destFile, true);

                image_PlanImg.Source = new BitmapImage(new Uri(destFile));

            }
        }

        private void button_catAdd_Click(object sender, RoutedEventArgs e)
        {

            ProjectCatogry winProjCat = new ProjectCatogry();
            winProjCat.ShowDialog();

        }

        private void button_projType_add_Click(object sender, RoutedEventArgs e)
        {
            ProjectTypes winProjType = new ProjectTypes();
            winProjType.ShowDialog();
        }








        private void button_UpdateGrids_Click(object sender, RoutedEventArgs e)
        {

        }

        private void comboBox_projCatogory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            if (listView1.Items.Count == 0)
            {
                AddRow();
            }
            else
            {
                listView1.SelectedIndex = 0;
            }
            setDataChanged(false);
            textBox_longitude.Focus();
        }

        private void button_close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// addButton click event handler.
        /// Add a new row to the ListView.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_NewRecord_Click(object sender, RoutedEventArgs e)
        {
            setDataChanged(true);
            AddRow();
        }

        private void setDataChanged(bool value)
        {
            dataChanged = value;

        }

        private void AddRow()
        {
            Data_ProjectGridLocation oLoc = new Data_ProjectGridLocation();
            oLoc.Grid_id = listView1.Items.Count + 1;

            listObjGrdLoc.Add(oLoc);

            listView1.Items.Add(new Data_ProjectGridLocation("", ""));
            listView1.SelectedIndex = listView1.Items.Count - 1;

            textBox_latitude.Text = "";
            textBox_longitude.Text = "";
            textBox_longitude.Focus();
        }


        /// <summary>
        /// Refreshses the ListView row with given values
        /// </summary>
        /// <param name="value1">Value for column 1</param>
        /// <param name="value2">Value for column 2</param>
        private void textBox_longitude_TextChanged(object sender, TextChangedEventArgs e)
        {

            RefreshListView(textBox_longitude.Text, textBox_latitude.Text);

        }

        private void textBox_latitude_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshListView(textBox_longitude.Text, textBox_latitude.Text);
        }

        private void RefreshListView(string value1, string value2)
        {
            Data_ProjectGridLocation lvc = (Data_ProjectGridLocation)listView1.SelectedItem; //new ListViewClass(value1, value2);
            if (lvc != null && !stopRefreshControls)
            {
                try
                {
                    setDataChanged(true);
                    var query = from t in listObjGrdLoc
                                where t.Grid_id == listView1.SelectedIndex + 1
                                select t;

                    if (query.Count() > 0)
                    {
                        query.Single().Loc_latitude = value1;
                        query.Single().Loc_longitude = value2;
                    }

                    if (value1 != "")
                    {
                        lvc.Loc_longitude = value1;
                    }

                    if (value2 != "")
                    {
                        lvc.Loc_latitude = value2;
                    }
                    listView1.Items.Refresh();
                }
                catch (InvalidOperationException)
                {
                    MessageBox.Show("Values Are Added Already", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (Exception) { }
            }


        }

        /// <summary>
        /// removeButton click event handler
        /// Removes the selected row from the ListView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>


        private void button_RemoveRecord_Click(object sender, RoutedEventArgs e)
        {
            setDataChanged(true);
            int selectedIndex = listView1.SelectedIndex;


            listObjGrdLoc.RemoveAt(selectedIndex);

            Project_AreaGrids ObjGrd1 = new Project_AreaGrids();


            listView1.Items.Remove(listView1.SelectedItem);

            // if no rows left, add a blank row
            if (listView1.Items.Count == 0)
            {
                AddRow();
            }
            else if (selectedIndex <= listView1.Items.Count - 1) // otherwise select next row
            {
                listView1.SelectedIndex = selectedIndex;

            }
            else // not above cases? Select last row
            {
                listView1.SelectedIndex = listView1.Items.Count - 1;

            }
        }

        /// <summary>
        /// listView1 SelectionChnaged event handler.
        /// Updates the textboxes with values in the row.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Data_ProjectGridLocation lvc = (Data_ProjectGridLocation)listView1.SelectedItem;
            if (lvc != null)
            {
                stopRefreshControls = true;
                textBox_longitude.Text = lvc.Loc_longitude;
                textBox_latitude.Text = lvc.Loc_latitude;
                stopRefreshControls = false;



            }
        }


        /// <summary>
        /// textBox KeyDown event handler.
        /// Restores old value, if Esc key is pressed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_longitude_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                RestoreOldValue(sender);
            }
        }



        private void textBox_latitude_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                RestoreOldValue(sender);
            }
        }
        /// <summary>
        /// Restores old value, saved in Tag property, to textbox.
        /// </summary>
        /// <param name="sender"></param>
        private void RestoreOldValue(object sender)
        {
            TextBox myText = (TextBox)sender;

            if (myText.Text != myText.Tag.ToString())
            {
                myText.Text = myText.Tag.ToString();
                myText.SelectAll();
            }
        }

        /// <summary>
        /// textBox2 GotFocus event handler.
        /// Store the current value and select all text.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_latitude_GotFocus(object sender, RoutedEventArgs e)
        {
            StoreCurrentValue(sender);
            textBox_latitude.SelectAll();
        }

        private void textBox_longitude_GotFocus(object sender, RoutedEventArgs e)
        {

            StoreCurrentValue(sender);
            textBox_longitude.SelectAll();
        }

        /// <summary>
        /// Saves the current value to the Tag property of textbox.
        /// </summary>
        /// <param name="sender"></param>
        private void StoreCurrentValue(object sender)
        {
            TextBox myText = (TextBox)sender;
            myText.Tag = myText.Text;
        }

        private void button_ClearAll_Click(object sender, RoutedEventArgs e)
        {
            SaveButton.IsEnabled = true;
            textBox_projname.Text = "";
            comboBox_projType.SelectedIndex = -1;
            comboBox_projCatogory.SelectedIndex = -1;
            textBox_appAgency.Text = "";
            textBox_client.Text = "";
           // combobox_TeamLeader.SelectedIndex = -1;
           // lblConsultent.Content = "";
            textBox_location.Text = "";
            textBox_projname.Focus();





        }

        private void comboBox_projCatogory_DropDownOpened(object sender, EventArgs e)
        {
            FillPrjCategories();
        }

        private void comboBox_projType_DropDownOpened(object sender, EventArgs e)
        {
            FillPrjType();

        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }
          
    }
}
